﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using log4net;
using Matrix.Common.Utility;
using Matrix.Common.Utility.Files;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.BLL.WxInterfaceFunc;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.MatrixCloudApi;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Matrix.MaKaYunShang.MagWeb.Controllers
{
    public class BaseController : Controller
    {
        public readonly ILog Logger = LogManager.GetLogger(typeof(BaseController));
        //删除数据时需输入验证码（临时措施）
        public static readonly string DeleteVCode = ConfigurationManager.AppSettings["DeleteVCode"];
        public static readonly string ExportAddress = ConfigurationManager.AppSettings["ExportAddress"];

        //码云卡商家端MCID
        public static string MkysMcMagMcId = ConfigurationManager.AppSettings["MkysMcMagMcId"];
        //码云卡MCID
        public static string MkysMcId = ConfigurationManager.AppSettings["MkysMcId"];

        public MatrixCloudCenterInterFuncBll MatrixCloudCenterInterFuncBllobj = new MatrixCloudCenterInterFuncBll();

        /// <summary>
        ///     当前登录用户信息
        /// </summary>
        public MagUser CurrentUser;
        public List<MagModules> MagModules;
        public BaseController()
        {
            CurrentUser = System.Web.HttpContext.Current.Session["user"] as MagUser;
            if (CurrentUser == null && System.Web.HttpContext.Current.Request.Cookies["user"] != null)
            {
                var username = System.Web.HttpContext.Current.Request.Cookies["user"].Values["u"];
                var password = System.Web.HttpContext.Current.Request.Cookies["user"].Values["p"];
                if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
                {
                    username = EncryptionLib.Decrypt(username, Encoding.UTF8);
                    var model = MagUserBLL.Instance.GetModel(username, password);
                    if (model != null)
                    {
                        System.Web.HttpContext.Current.Session["user"] = model;
                        CurrentUser = model;
                        ViewBag.CurrentUser = CurrentUser;
                        ViewBag.HtmlNavMenu = ReadAndInsertNavMenuHtml(CurrentUser);
                    }
                    else
                    {
                        var newcookie = new HttpCookie("user") { Expires = DateTime.Now.AddDays(-1) };
                        System.Web.HttpContext.Current.Response.Cookies.Add(newcookie);
                    }
                }
                else
                {
                    var newcookie = new HttpCookie("user") { Expires = DateTime.Now.AddDays(-1) };
                    System.Web.HttpContext.Current.Response.Cookies.Add(newcookie);
                }
            }
            else if (CurrentUser != null)
            {
                ViewBag.CurrentUser = CurrentUser;
                ViewBag.HtmlNavMenu = ReadAndInsertNavMenuHtml(CurrentUser);
                MagModules = System.Web.HttpContext.Current.Session["userModules" + CurrentUser.Id] as List<MagModules>;
            }
            if (CurrentUser != null && MagModules == null)
            {
                var allowedModules = GetAllowedModules(CurrentUser);
                allowedModules.RemoveAll(s => s == null);
                System.Web.HttpContext.Current.Session["userModules" + CurrentUser.Id] = allowedModules;
                MagModules = allowedModules;
            }

        }
        /// <summary>
        ///     获取当前用户所有有权限执行的动作
        /// </summary>
        /// <returns></returns>
        private List<MagModules> GetAllowedModules(MagUser user)
        {
            var lsModuleIds =
                MagRoleModulePermissionBLL.Instance.GetModelListByRoleId(user.RoleId).Select(x => x.ModuleId).ToList();
            return lsModuleIds.Select(moduleId => MagModulesBLL.Instance.GetModel(moduleId)).ToList();
        }
        /// <summary>
        ///     从用户浏览器缓存中读取菜单，减少服务器压力，降低数据库IO
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        private string ReadAndInsertNavMenuHtml(MagUser user)
        {
            string userNavMenu;
            var menuCookie = System.Web.HttpContext.Current.Request.Cookies["UserNavMenuCookie"];

            if (menuCookie != null)
            {
                userNavMenu = HttpUtility.UrlDecode(menuCookie.Values["strMenu"], Encoding.GetEncoding("UTF-8"));
                if (!string.IsNullOrEmpty(userNavMenu)) return userNavMenu;

                var strMenu = HttpUtility.UrlEncode(RenderNavigationMenu(user), Encoding.GetEncoding("UTF-8"));
                menuCookie.Values["strMenu"] = strMenu;
                userNavMenu = HttpUtility.UrlDecode(strMenu, Encoding.GetEncoding("UTF-8"));
            }
            else
            {
                var dt = DateTime.Now;
                var ts = new TimeSpan(1, 0, 0, 0, 0);
                var newMenuCookie = new HttpCookie("UserNavMenuCookie") { Expires = dt.Add(ts) };

                newMenuCookie.Values["userId"] = user.Id.ToString();
                newMenuCookie.Values["strMenu"] = HttpUtility.UrlEncode(RenderNavigationMenu(user), Encoding.GetEncoding("UTF-8"));
                System.Web.HttpContext.Current.Response.Cookies.Add(newMenuCookie);

                userNavMenu = HttpUtility.UrlDecode(newMenuCookie.Values["strMenu"], Encoding.GetEncoding("UTF-8"));
            }

            return userNavMenu;
        }

        /// <summary>
        ///     根据权限渲染导航栏
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        private string RenderNavigationMenu(MagUser user)
        {
            var strHtmlNav = string.Empty;

            if (user == null) return strHtmlNav;

            // 获取当前用户的能访问的所有模块ID
            var lsModuleIds =
                MagRoleModulePermissionBLL.Instance.GetModelListByRoleId(user.RoleId).Select(x => x.ModuleId).ToList();

            // 店铺管理员可见所有模块，否则根据用户拥有的模块ID查找出模块
            var lsModules = user.IsSuper == 1
                ? MagModulesBLL.Instance.GetModelList()
                : lsModuleIds.Select(moduleId => MagModulesBLL.Instance.GetModel(moduleId)).ToList();

            // 根据模块查找出模块主类ID
            var lsModuleCateIds = lsModules.Select(x => x.ModuleCate).Distinct().ToList();
            foreach (var moduleCateId in lsModuleCateIds)
            {
                // 遍历主类找出组Html
                var htmlSubMenu = string.Empty;
                var moduleCate = MagModuleCateBLL.Instance.GetModel(moduleCateId);
                strHtmlNav += moduleCate.HtmlText;
                var cateId = moduleCateId;
                var modules = lsModules.Where(x => x.ModuleCate == cateId).Select(x => x.HtmlText);
                // 遍历子类模块并找出Html替换主类的{subMenu} 完成菜单组装
                htmlSubMenu = modules.Aggregate(htmlSubMenu, (current, module) => current + module);
                strHtmlNav = strHtmlNav.Replace("{subMenu}", htmlSubMenu);
            }
            return strHtmlNav;
        }

        /// <summary>
        ///     获得当前页面客户端的IP
        /// </summary>
        /// <returns>当前页面客户端的IP</returns>
        public string GetIP()
        {
            var result = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            if (string.IsNullOrEmpty(result))
                result = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(result))
                result = System.Web.HttpContext.Current.Request.UserHostAddress;
            if (string.IsNullOrEmpty(result) || !IsIP(result))
                return "127.0.0.1";
            return result;
        }

        /// <summary>
        ///     是否为ip
        /// </summary>
        public bool IsIP(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

        /// <summary>
        ///     获取加密或解密字符串
        /// </summary>
        /// <param name="type">1：加密、2：解密</param>
        /// <param name="content"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetEnDeCode(string type, string content)
        {
            var result = new { obj = "" };

            try
            {
                if (type == "1")
                {
                    result = new { obj = EncryptionLib.Encrypt(content, Encoding.UTF8) };
                }
                else if (type == "2")
                {
                    result = new { obj = EncryptionLib.Decrypt(content, Encoding.UTF8) };
                }
            }
            catch (Exception)
            {
            }
            return Json(result);
        }

        /// <summary>
        ///     获取配置文件appSettings值
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetAppSetValue()
        {
            var keyName = Request["keyName"];
            var keyValue = ConfigLib.GetAppSettings(keyName);
            var resultJson = new JsonModel.ExecResultSimple
            {
                result = true,
                msg = keyValue
            };

            return Json(resultJson);
        }

        /// <summary>
        ///     获取省市区联动数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetAreaList()
        {
            var areaId = int.Parse(Request["areaId"]);
            var list = AreaInfoBLL.Instance.GetAreaListByParentId(areaId);

            return Json(list);
        }

        /// <summary>
        ///     异常处理
        /// </summary>
        /// <param name="filterContext">异常上下文</param>
        /// <returns>异常提示信息</returns>
        protected override void OnException(ExceptionContext filterContext)
        {
            var exceptionResult = new Result
            {
                Status = false,
                Message = "系统错误，请重试！"
            };
            Logger.Error("系统未捕获异常:" + filterContext.Exception);
            if (ConfigurationManager.AppSettings["IsShowError"] == "false")
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = Json(exceptionResult, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    filterContext.Result = RedirectToAction("Error500", "Error");
                }
                filterContext.ExceptionHandled = true;
            }
        }

        /// <summary>
        ///     上传单张图片
        /// </summary>
        /// <param name="strFileRequest">Request.File[strFileRequest], 请求文件的名称</param>
        /// <param name="storeToPath">图片存储地址（相对路径，该图片对应的文件夹地址）</param>
        /// <param name="setWidth"></param>
        /// <param name="setHeight"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        protected string UploadImage(string strFileRequest, string storeToPath, int setWidth, int setHeight,
            string mode = "Cut")
        {
            var imageHelper = new ImagesFile();
            var file = Request.Files[strFileRequest];
            if (file == null || file.FileName.Length <= 0) return "";

            var uploadPath = ConfigurationManager.AppSettings["ImgFileUploadPath"] + "TempImg" + storeToPath;
            var extensionStr = file.FileName.Substring(file.FileName.LastIndexOf(".", StringComparison.Ordinal));
            var fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + extensionStr;

            if (!Directory.Exists(uploadPath)) Directory.CreateDirectory(uploadPath);

            uploadPath += fileName;
            file.SaveAs(uploadPath);

            var dt = DateTime.Now;
            var newPathStr = ConfigurationManager.AppSettings["ImgFileUploadPath"];
            var tempPath = storeToPath + dt.Year + "/" + dt.Month + "/" + dt.Day + "/";
            newPathStr += tempPath;

            imageHelper.CreateDirectoryOrExist(newPathStr);
            imageHelper.CutPic(uploadPath, newPathStr + fileName, setWidth, setHeight, mode);
            imageHelper.DeleteFileZhi(uploadPath);

            return tempPath + fileName;
        }


        /// <summary>
        ///     返回处理过时间的json
        /// </summary>
        /// <param name="Data"></param>
        /// <returns></returns>
        protected ContentResult JsonDate(object Data)
        {
            var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };

            return Content(JsonConvert.SerializeObject(Data, Formatting.Indented, timeConverter));
        }


        /// <summary>
        ///     去单引号
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        protected string SqlSafe(string value)
        {
            return value.Replace("'", "''");
        }

        public string AlterMessage(string msg, string returnUrl)
        {
            return
            msg = string.IsNullOrEmpty(msg) ? "<iframe src=\"/Home/Message?Message=无访问权限，请联系您的上级管理员!&Url=" + returnUrl + "\" width='100%' height='98%' scrolling='no' style=' border: 0px;'></iframe>" :
            msg;
            return "<iframe src=\"/Home/Message?Message=" + msg +
            "!&Url=" + returnUrl + "\" width='100%' height='98%' scrolling='no' style=' border: 0px;'></iframe>";
        }

        /// <summary>
        /// 获取当前接口当前云迈云项目资料
        /// </summary>
        /// <param name="pjMcId"></param>
        /// <returns></returns>
        protected MatrixCloudProjectInfo GetCurrentMatrixCloudProjectInfo(string pjMcId)
        {
            var localProjectInfo = MatrixCloudProjectInfoBLL.Instance.GetModelByPjMcId(pjMcId);
            if (localProjectInfo == null || localProjectInfo.Id == 0 ||
                string.IsNullOrWhiteSpace(localProjectInfo.PjMcId))
            {
                return null;
            }

            var checkResult =
                MatrixCloudCenterInterFuncBllobj.CheckAndGetMatrixCloudProjectInfo(localProjectInfo.PjCode);
            return checkResult.Status ? checkResult.Data : null;
        }

        protected MxApiWechatInfo GetWechatInfoByProjectInfo(string pjMcId, string pjSecret)
        {
            var resultWechatInfo = MatrixCloudCenterInterFuncBllobj.GetWechatInfo(pjMcId, pjSecret);
            return resultWechatInfo.Status ? resultWechatInfo.Data : null;
        }

    }
}